#include <stdio.h>

#include <iostream>

#include "./Ucontext.h"

using namespace std;

void cofunc1(schedule_t *ps, void * arg)
{
	cout << "func1....1" << endl;
	cout << "func1....2" << endl;
	return ;
}

void cofunc2(schedule_t *ps, void * arg)
{
    cout << "func2....1" << endl;
    cout << "func2....2" << endl;
    return ;
}
void cofunc3(schedule_t *ps, void * arg)
{
    cout << "func3....1" << endl;
	ps->uthread_yield();
    cout << "func3....2" << endl;
    return ;
}

void schedule_main() {
	schedule_t sche;
	void *arg;
	int id1 = sche.uthread_create(std::bind(cofunc2,&sche,arg));
	int id2 = sche.uthread_create(std::bind(cofunc3,&sche,arg));
	while(!sche.schedule_finished()) 
	{
		sche.uthread_resume(id1);
		sche.uthread_resume(id2);
	}
	cout << "schedule_main end" << endl;
}

void coroutine_switch_performance_test_func(schedule_t *ps, int times)
{
	int i = 0;
	while(i < 1000000 * times){
		ps->uthread_yield();
		++i;
	}
}
void coroutine_performance_test() {
    schedule_t sche;
    int times = 10;
    int id = sche.uthread_create(std::bind(coroutine_switch_performance_test_func, &sche, times));
    clock_t start, end;
    start = clock();
    while(!sche.schedule_finished()) {
        sche.uthread_resume(id);
    }
    end = clock();
    printf("total %d times context switch\ntake Time：%lf ms\navg time: %lf us\n",
        times*1000000,
        (double)(end - start)/1000,
        (double)(end - start)/(times*1000));
}

int main()
{
	schedule_main();
	coroutine_performance_test();

}
